package com.example.demo.config;

import io.shardingjdbc.core.api.algorithm.sharding.PreciseShardingValue;
import io.shardingjdbc.core.api.algorithm.sharding.standard.PreciseShardingAlgorithm;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.concurrent.atomic.AtomicReference;

public class DateAlgorithm implements PreciseShardingAlgorithm<Date> {
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Date> preciseShardingValue) {
        Date value = preciseShardingValue.getValue();
        String logicTableName = preciseShardingValue.getLogicTableName();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");
        String sub = simpleDateFormat.format(value);
        AtomicReference<String> ret = new AtomicReference<>("");
        collection.forEach(c -> {
            if (logicTableName.equals(c)) {
                ret.set(c + sub);
            }
        });
        return ret.get();
    }
}
